<?php
include_once 'connect.php';
$action = $_GET['action'];
$id = 1;
$ip = get_client_ip();

if($action == like){
	likes(1,$id,$ip);
}elseif($action == unlike){
	likes(0,$id,$ip);
}else{
	echo jsons($id);
}

function likes($type,$id,$ip){
	$ip_sql = mysql_query("SELECT ip FROM votes_ip WHERE vid = '$id' AND ip = '$ip'");
	$count = mysql_num_rows($ip_sql);
	if($count == 0){
		if($type == 1){
			$sql = "UPDATE votes SET likes=likes+1 WHERE id = '$id'";
		}else{
			$sql = "UPDATE votes SET unlikes=unlikes+1 WHERE id = '$id'";
		}
		mysql_query($sql);
		$sql_in = "INSERT INTO votes_ip(vid,ip) VALUES ('$id','$ip')";
		mysql_query($sql_in);
		if(mysql_insert_id() > 0){
			echo jsons($id);
		}else{
			$arr['success'] = 0;
			$arr['msg'] = '操作失败';
			echo json_encode($arr);
		}
	}else{
			$msg = $type == 1 ? '您已经顶过了' : '您已经踩过了';
			$arr['success'] = 0;
			$arr['msg'] = $msg;
			echo json_encode($arr);
		}
}
//初始化投票的函数，读取相应信息的投票数，并计算百分比，以json格式输出
function jsons($id){
	$query = mysql_query("SELECT * FROM votes WHERE id='$id'");
	$row = mysql_fetch_array($query);
	$like = $row['likes'];
	$unlike = $row['unlikes'];
	$arr['success'] = 1;
	$arr['like'] = $like;
	$arr['unlike'] = $unlike;
	$like_percent = round($like/($like+$unlike),3)*100;
	$arr['like_percent'] = $like_percent.'%';
	$arr['unlike_percent'] = (100-$like_percent).'%';
	return json_encode($arr);
}

function get_client_ip(){
	static $realip = NULL;
	if ($realip !== NULL)
	{
		return $realip;
	}
	if (isset($_SERVER))
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			/* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
			foreach ($arr as $ip)
			{
				$ip = trim($ip);
				if ($ip != 'unknown')
				{
					$realip = $ip;
					break;
				}
			}
		}
			
		elseif (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else
		{
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}
	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	
	$realip = ! empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
	
	return $realip;
}
?>
